package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.impl.conn.Wire;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.exercise.AndroidCamera.ManageFriendActivity.deleteFriendAsync;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData.Item;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
/*
기능 : 게시물 작성
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class WritePostActivity extends BaseActivity {

   protected static final int REQ_CODE_PICK_PICTURE = 0;
   private GridView grid;
   private Intent intent;
   private ArrayList<Intent> image_intent;
   private ArrayList<Bitmap> arrBitmap;
   
	private static Uri photo_uri;
	
	public final static int CAMERA_SHOOT = 100; //intent 에 사용될 요청코드
	public final static int GET_PICTURE = 200;
	
	private Bitmap bitmap; // preview 안에 들어갈 이미지.
	private ImageView preview; // preview
	private String[] photo_menu = {"사진 촬영", "갤러리", "동영상 촬영"}; // 다이얼로그 메뉴에 쓸 어레이.
   
   RadioButton radio;
   RadioGroup group, showgroup;
   EditText title, contents;
   String board_id;
   private int flag=0;
   Intent mIntent;
   String userID;
   String locationID;
   int groupId=1;
   int imageCount=0;

   private ProgressDialog waitDialog;

	
	ArrayList<String> groupNameArray;
	ArrayList<String> groupIdArray;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_write_post);
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      
      image_intent = new ArrayList<Intent>();
      userID = getIntent().getExtras().getString("userID");
      locationID = getIntent().getExtras().getString("locationID");
      
      // select group  
      group = (RadioGroup) findViewById(R.id.grouplist);
      showgroup = (RadioGroup) findViewById(R.id.GroupRadio);	
      Button btnCamera = (Button) findViewById(R.id.btnCamera);
      title = (EditText) findViewById(R.id.editTitle);
      contents = (EditText) findViewById(R.id.editContents);
      
      groupNameArray = new ArrayList<String>();
      groupIdArray = new ArrayList<String>();
      arrBitmap = new ArrayList<Bitmap>();
      
      getActionBar().setDisplayHomeAsUpEnabled(true);
      
      groupSyncTask groupSync = new groupSyncTask();
      groupSync.execute();
      
      btnCamera.setOnClickListener(new View.OnClickListener() {
         @Override
 		public void onClick(View v) {
				new AlertDialog.Builder(WritePostActivity.this)
				.setTitle("카메라 메뉴")
				.setItems(photo_menu, onChoice) // photo_menu를 띄우고 선택시 onChoice로
				.setCancelable(false) // back 버튼 못쓰게.
				.setNegativeButton("닫기", null)
				.show();
		}
      });
      
	
    showgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			// TODO Auto-generated method stub
			
			switch(checkedId){
			case R.id.radioGroup:
				flag=1;
				
				findViewById(R.id.radiogrouplayout).setVisibility(View.VISIBLE);
				findViewById(R.id.writelayout).setVisibility(View.GONE);				        
				break;
				
			case R.id.radioAll:
				groupId = 1;
				break;
			
			case R.id.radioFriend:
				groupId = 14;
				break;
			}
		}
    });
    
    group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(RadioGroup radiogroup, int checkedId) {
			// TODO Auto-generated method stub
				if(checkedId==radiogroup.getChildAt(checkedId).getId()){
					groupId = Integer.valueOf(groupIdArray.get(checkedId));
				}
		}
	});
        
	getActionBar().setTitle("Post Memories");
	getActionBar().setDisplayShowHomeEnabled(false);
   }
      
   //Back button Event
   public void onBackPressed() {
	   if(flag==0){
		   finish();
	   }
	   else{
		   flag=0;
		   findViewById(R.id.radiogrouplayout).setVisibility(View.GONE);
		   findViewById(R.id.writelayout).setVisibility(View.VISIBLE);
	   }
	}
   
   public String getRealPathFromUri(Uri contentUri){
	   String[] proj = {MediaStore.Images.Media.DATA};
	   Cursor cursor = managedQuery(contentUri, proj, null, null, null);
	   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	   cursor.moveToFirst();
	   return cursor.getString(column_index);
   }

   BitmapFactory.Options options;
   Bitmap bmp;
   @SuppressLint("NewApi") @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data){
	   
        	if(requestCode == REQ_CODE_PICK_PICTURE){
                 if(resultCode == Activity.RESULT_OK){
                	 grid = (GridView)findViewById(R.id.gridView);
                	 options = new BitmapFactory.Options();
                	 
                	 try{
                    	 options.inSampleSize = 4;
                	 bmp = BitmapFactory.decodeFile(getRealPathFromUri(data.getData()), options);
                	 }
                	 catch (OutOfMemoryError e){
                    	 options.inSampleSize = 10;
                    	 bmp = BitmapFactory.decodeFile(getRealPathFromUri(data.getData()),options);
                	 }
                	 arrBitmap.add(bmp);

        	         grid.setAdapter(new ImageAdapter(this, arrBitmap));
        	         image_intent.add(data);
        	         imageCount++;
          }
      }
      else if(requestCode == CAMERA_SHOOT){
			if(resultCode == Activity.RESULT_OK){ // 카메라로 사진을 찍고 저장했을때
				
           	 grid = (GridView)findViewById(R.id.gridView);

	        	Uri imgUri= photo_uri;
				try {
				AssetFileDescriptor afd = getContentResolver().openAssetFileDescriptor(imgUri, "r");       
					BitmapFactory.Options opt = new BitmapFactory.Options(); 
					opt.inSampleSize = 10;
					bmp = BitmapFactory.decodeFileDescriptor(afd.getFileDescriptor(), null, opt);
					
					Log.d("path","try문 들어옴");
					Log.d("path",bmp+"");

			//		selPhoto = Images.Media.getBitmap( getContentResolver(), imgUri );
				} catch (OutOfMemoryError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
           	 arrBitmap.add(bmp);

   	         grid.setAdapter(new ImageAdapter(this, arrBitmap));
   	         
	//		 String physical_path = photo_uri.toString().substring(7).replaceAll("%3B", ";").replaceAll("%20"," ");
	//		 Uri a = Uri.parse(physical_path);
				
        	 
			 Intent data2 = new Intent();
			 data2.setDataAndType(photo_uri,"image/*");

   	         image_intent.add(data2);
   	         imageCount++;
   	  }
   }
        	 grid.setOnItemClickListener(new OnItemClickListener() {
                 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                	 ImageView bigImage = (ImageView) findViewById(R.id.bigimgview);
                	 bigImage.setImageBitmap(BitmapFactory.decodeFile(getRealPathFromUri(image_intent.get(position).getData())));
                	 getActionBar().hide();
                	 findViewById(R.id.bigimglayout).setVisibility(View.VISIBLE);
                 }
           });
        	 
        	 findViewById(R.id.bigimglayout).setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					getActionBar().show();
               	 findViewById(R.id.bigimglayout).setVisibility(View.GONE);
					return false;
				}
			});
        	 
        	 grid.setOnItemLongClickListener(new OnItemLongClickListener() {

  				@Override
  				public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
  					// TODO Auto-generated method stub
  					
  					new AlertDialog.Builder(WritePostActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("사진 삭제").setMessage("사진을 지우시겠습니까?")
  			    	.setNegativeButton("아니요", null).setPositiveButton("예", new DialogInterface.OnClickListener()
  			 	   {
  			 	     @Override
  			 	     public void onClick( DialogInterface dialog, int which )
  			 	     {
  			 	    	arrBitmap.remove(position);
  			 	    	image_intent.remove(position);
  			 	    	grid.setAdapter(new ImageAdapter(WritePostActivity.this, arrBitmap));
  			 	    	imageCount--;
  			 	     }
  			 	   }).show(); 
  					
  					return false;
  				}
  			});
  }
   
   public boolean onCreateOptionsMenu(Menu menu) {

      // Inflate the menu; this adds items to the action bar if it is present.
		   getMenuInflater().inflate(R.menu.write_post, menu);
      return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
       String text = null;
        
          switch(item.getItemId()){
          case android.R.id.home:
              text = "Application icon";
              onBackPressed();
              break;
               
          case R.id.cancel:
              onBackPressed();
              break;
              
          case R.id.save:
        	  if(flag==0){
        		  new AlertDialog.Builder(WritePostActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("게시물 등록").setMessage("게시물을 등록하시겠습니까?")
					.setNeutralButton("아니오", null)
					.setPositiveButton("예", new DialogInterface.OnClickListener()
				   {
				     @Override
				     public void onClick( DialogInterface dialog, int which )
				     {
							writePostAsyncTask postAsync = new writePostAsyncTask();
							postAsync.execute();
				     }
				   }).show(); 
        	  }
        	  else{
        		  flag=0;
        		  findViewById(R.id.radiogrouplayout).setVisibility(View.GONE);
        		  findViewById(R.id.writelayout).setVisibility(View.VISIBLE);
        	  }
        	  break;
               
          default:
              return false;
          }
          return true;
   }
   
   
   public String makeBitmapImage(int i) {
			Bitmap bitmapOrg = null;
			InputStream stream = null;
			try {
				stream = getContentResolver().openInputStream(image_intent.get(i).getData());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bitmapOrg = BitmapFactory.decodeStream(stream);
			   ByteArrayOutputStream bao = new ByteArrayOutputStream();
			   bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 50, bao);
			   bitmapOrg.recycle();
			   byte [] ba = bao.toByteArray();
			   String ba1 = Base64.encodeToString(ba, Base64.NO_WRAP);
			   return ba1;
   }
   
   protected String[] write_post_image(Context context, String image, int picture_num){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		try{
      	StringBuilder builder = new StringBuilder();
      	
      	URL url = new URL("http://54.199.194.197/write_board_img.php");
      	conn = (HttpURLConnection)url.openConnection();
      	
      	if(conn != null){
      		conn.setConnectTimeout(15000);
      		conn.setReadTimeout(15000);

      		conn.setDefaultUseCaches(false);
          	conn.setDoInput(true);
          	conn.setDoOutput(true);
          	conn.setRequestMethod("POST");
          	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
          	
          	StringBuffer buffer = new StringBuffer();
            buffer.append("board_id").append("=").append(board_id).append("&");                 
            buffer.append("contents_id").append("=").append(picture_num+"").append("&");
            buffer.append("image").append("=").append(image);

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
              
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
             
          	String line;
          	while((line = br.readLine()) != null){
          	   builder.append(line);
          	}
             
          	br.close();
          	
          	pString =  builder.toString();
      	}else{
      		
      		throw new Exception("network error");
      	}
      	
      }catch(SocketTimeoutException se){
      	
      	result[1] = "network error";
      	
      }catch(Exception e){
      	
      	result[1] = e.getMessage();
      	
      }finally{
      	
      	if(conn != null)
      		conn.disconnect();

      	if(br != null){
      		try {
      			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
      	}
      }
    
      return result;
	}
   
   protected String[] write_post_text(Context context){
	   String editContents = contents.getText().toString();
	   
	   String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/write_board_txt.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false);
           	conn.setDoInput(true); 
           	conn.setDoOutput(true); 
           	conn.setRequestMethod("POST"); 
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 

           	StringBuffer buffer = new StringBuffer();
            buffer.append("board_id").append("=").append(board_id).append("&");                 
            buffer.append("contents_id").append("=").append("1").append("&");
            buffer.append("text").append("=").append(editContents);
            Log.d("buffer", buffer+"");
               
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();

            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	pString =  builder.toString();
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
     
       return result;
	}
   
   protected String[] write_post(Context context){
	   String editTitle = title.getText().toString();
	   String[] info = new String[8];
	   
	   SimpleDateFormat sdf;
	   String strCurDate;
	   sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
	   strCurDate = sdf.format(new java.util.Date());

	   info[0] = locationID; // location_id
	   info[1] = "0"; // group_id
	   info[2] = userID; // user_id
	   info[3] = strCurDate; // date
	   info[4] = image_intent.size()+""; // draw
	   info[5] = "0"; // like
	   info[6] = editTitle;
	   
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/write_board.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false);
       		conn.setDoInput(true);
           	conn.setDoOutput(true);
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
           	
           	StringBuffer buffer = new StringBuffer();
           	
            buffer.append("location_id").append("=").append(info[0]).append("&");
            buffer.append("group_id").append("=").append(info[1]).append("&");
            buffer.append("user_id").append("=").append(info[2]).append("&");
            buffer.append("date").append("=").append(info[3]).append("&");
            buffer.append("photo_num").append("=").append(info[4]).append("&");
            buffer.append("like_board").append("=").append(info[5]).append("&");
            buffer.append("group_id").append("=").append(Integer.toString(groupId)).append("&");
            buffer.append("title").append("=").append(info[6]);
            
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
               
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	board_id = pString;
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
     
       return result;
	}
   
   protected String[] request_board_id(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/request_board_id.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);
       		conn.setReadTimeout(15000);

       		conn.setDefaultUseCaches(false); 
       		conn.setDoInput(true);
           	conn.setDoOutput(true);
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
           	
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	board_id = pString;
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
     
       return result;
	}
   
   public class writePostAsyncTask extends AsyncTask<String, String, String> {
	 @Override
	protected void onPreExecute() {
		 waitDialog = new ProgressDialog(WritePostActivity.this, R.style.MyProgressTheme);
			waitDialog.setTitle("게시물 쓰기");
			waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			waitDialog.setMessage("게시물을 올리는 중입니다...");
			waitDialog.setIcon(R.id.icon);
			waitDialog.setIndeterminate(true);
			waitDialog.setCancelable(true);
			waitDialog.show();
		super.onPreExecute();
	}
	   @Override
	protected String doInBackground(String... params) {
		write_post(WritePostActivity.this);
		return null;
	}
	   @Override
	protected void onPostExecute(String result) {
		writeTxtAsyncTask txtAsync = new writeTxtAsyncTask();
		txtAsync.execute();
		super.onPostExecute(result);
	}
	   @Override
	protected void onCancelled() {
		super.onCancelled();
	}
   }
   
   public class writeTxtAsyncTask extends AsyncTask<String, String, String> {
	   @Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		   @Override
		protected String doInBackground(String... params) {
			write_post_text(WritePostActivity.this);
			return null;
		}
		   @Override
		protected void onPostExecute(String result) {
			if(image_intent.size()!=0) {
				writeImgAsyncTask ImgAsync = new writeImgAsyncTask();
				ImgAsync.execute();
			} else {
				addSyncTask addAsync = new addSyncTask();
	        	  addAsync.execute();
			}
			super.onPostExecute(result);
		}
		   @Override
		protected void onCancelled() {
			super.onCancelled();
		}
   }
   public class writeImgAsyncTask extends AsyncTask<String, String, String> {
	   String imageBase=null;
	   @Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		   @Override
		protected String doInBackground(String... params) {
			   for(int i=0;i<image_intent.size();i++) {
			
				imageBase = makeBitmapImage(i);
				write_post_image(WritePostActivity.this, imageBase, i);
			}
			return null;
		}
		   @Override
		protected void onPostExecute(String result) {
			addSyncTask addAsync = new addSyncTask();
	     	addAsync.execute();
			super.onPostExecute(result);
		}
		   @Override
		protected void onCancelled() {
			super.onCancelled();
		}
		
		}
   protected String[] add_board(Context context){
	   String editTitle = title.getText().toString();
	   String[] info = new String[8];
	   
	   SimpleDateFormat sdf;
	   String strCurDate;
	   sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
	   strCurDate = sdf.format(new java.util.Date());
	   
	   String pString = null;
	   HttpURLConnection conn = null;
	   BufferedReader br = null;
	   
	   String[] result = new String[2];
	   result[0] = "error"; //JSON flag
	   result[1] = null; //message
	   
	   try{
		   StringBuilder builder = new StringBuilder();
		   
		   URL url = new URL("http://54.199.194.197/add_board.php");
		   conn = (HttpURLConnection)url.openConnection();
		   
		   if(conn != null){
			   conn.setConnectTimeout(15000);
			   
			   conn.setReadTimeout(15000);

			   conn.setDefaultUseCaches(false);
			   conn.setDoInput(true);
			   conn.setDoOutput(true);
			   conn.setRequestMethod("POST");
			   conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			   
			   StringBuffer buffer = new StringBuffer();
			   
			   buffer.append("location_id").append("=").append(locationID);
			   
			   OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			   PrintWriter writer = new PrintWriter(outStream);
			   writer.write(buffer.toString());
			   writer.flush();
			   
			   InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
			   br = new BufferedReader(inputStream);
			   
			   String line;
			   while((line = br.readLine()) != null){
				   builder.append(line);
			   }
			   
			   br.close();
			   
			   pString =  builder.toString();
			   
		   }else{
			   
			   throw new Exception("network error");
		   }
		   
	   }catch(SocketTimeoutException se){
		   
		   result[1] = "network error";
		   
	   }catch(Exception e){
		   
		   result[1] = e.getMessage();
		   
	   }finally{
		   
		   if(conn != null)
			   conn.disconnect();
		   
		   if(br != null){
			   try {
				   br.close();
			   } catch (Exception e2) {
				   // TODO: handle exception
				   result[1] = e2.getMessage();
			   }
		   }
	   }
	   
	   return result;
   }
   
   public class addSyncTask extends AsyncTask<String, String, String>{
	   @Override
	   protected void onPreExecute() {
		   // TODO Auto-generated method stub
		   super.onPreExecute();
	   }
	   @Override
	   protected String doInBackground(String... params) {
		   // TODO Auto-generated method stub
		   add_board(WritePostActivity.this);
		   return null;
	   }
	   @Override
	   protected void onPostExecute(String result) {
		   // TODO Auto-generated method stub
     	  waitDialog.dismiss();
		  Toast.makeText(getApplicationContext(), "게시물이 등록되었습니다.", Toast.LENGTH_SHORT).show();
		   mIntent = new Intent(WritePostActivity.this, MainActivity.class);
	       mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	       mIntent.putExtra("userID", userID);
	       startActivity(mIntent);
		   super.onPostExecute(result);
	   }
	   @Override
	   protected void onCancelled() {
		   // TODO Auto-generated method stub
		   super.onCancelled();
	   }
   }
   
   protected String[] group_read(Context context){
	   String editTitle = title.getText().toString();
	   String[] info = new String[8];
	   
	   SimpleDateFormat sdf;
	   String strCurDate;
	   sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
	   strCurDate = sdf.format(new java.util.Date());
	   
	   String pString = null;
	   HttpURLConnection conn = null;
	   BufferedReader br = null;
	   
	   String[] result = new String[2];
	   result[0] = "error"; //JSON flag
	   result[1] = null; //message
	   
	   try{
		   StringBuilder builder = new StringBuilder();
		   
		   URL url = new URL("http://54.199.194.197/mylist_group.php");
		   conn = (HttpURLConnection)url.openConnection();
		   
		   if(conn != null){
			   conn.setConnectTimeout(15000);
			   
			   conn.setReadTimeout(15000);

			   conn.setDefaultUseCaches(false); 
			   conn.setDoInput(true);
			   conn.setDoOutput(true);
			   conn.setRequestMethod("POST");
			   conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
			   
			   StringBuffer buffer = new StringBuffer();
			   
			   buffer.append("user_id").append("=").append(userID);

			   OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			   PrintWriter writer = new PrintWriter(outStream);
			   writer.write(buffer.toString());
			   writer.flush();
			   
			   InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	           br = new BufferedReader(inputStream);
	              
	           	String line;
	           	while((line = br.readLine()) != null){
	           	   builder.append(line);
	           	}
	              
	           	br.close();
	           	
	           	pString =  builder.toString();
	           	Log.d("pString group in write post", pString);
	           	
	           	JSONObject jObject = new JSONObject(pString);
	           	JSONArray groupNameObject = new JSONArray(jObject.getString("group_name"));
	           	JSONArray groupIdObject = new JSONArray(jObject.getString("group_id"));
	           	
	           	for(int i=0; i<groupNameObject.length(); i++){
	           		groupNameArray.add(groupNameObject.getString(i));
	           		groupIdArray.add(groupIdObject.getString(i));
	           	}
			   
		   }else{
			   
			   throw new Exception("network error");
		   }
		   
	   }catch(SocketTimeoutException se){
		   
		   result[1] = "network error";
		   
	   }catch(Exception e){
		   
		   result[1] = e.getMessage();
		   
	   }finally{
		   
		   if(conn != null)
			   conn.disconnect();
		   
		   if(br != null){
			   try {
				   br.close();
			   } catch (Exception e2) {
				   // TODO: handle exception
				   result[1] = e2.getMessage();
			   }
		   }
	   }
	   
	   return result;
   }
   
   public class groupSyncTask extends AsyncTask<String, String, String>{
	   @Override
	   protected void onPreExecute() {
		   // TODO Auto-generated method stub
		   super.onPreExecute();
	   }
	   @Override
	   protected String doInBackground(String... params) {
		   // TODO Auto-generated method stub
		   group_read(WritePostActivity.this);
		   return null;
	   }
	   @Override
	   protected void onPostExecute(String result) {
		   // TODO Auto-generated method stub
		   super.onPostExecute(result);
		   Typeface tf = Typeface.createFromAsset(WritePostActivity.this.getAssets(), "fonts/whitechok.ttf");
		   TextView groupListText = (TextView) findViewById(R.id.groupListText);
		   groupListText.setTypeface(tf);
		   for(int i=0; i<groupIdArray.size(); i++){
			    radio = new RadioButton(WritePostActivity.this);
			    radio.setLayoutParams (new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				radio.setText(groupNameArray.get(i));
				radio.setId(i);
				radio.setTextColor(0xFF000000);
				radio.setTypeface(tf);
				radio.setTextSize(25);
				radio.setBackgroundResource(R.drawable.round_background_reverse);
//				radio.setGravity(Gravity.CENTER);
				group.addView(radio, i);
			}
	   }
	   @Override
	   protected void onCancelled() {
		   // TODO Auto-generated method stub
		   super.onCancelled();
	   }
   }

		DialogInterface.OnClickListener onChoice = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
					case 0: // 사진찍기 선택
						// sd 카드의 mount 여부 검사.
			    		if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
				    		// sd 카드 경로 가져오기
				    		String SD_path = Environment.getExternalStorageDirectory().getAbsolutePath(); //sd 카드 루트경로.
				    		SD_path += "/PostMemories"; // 사용할 폴더. 경로만 지정한것이지 실제로 폴더가 생기거나 한건 아니다.
				    		
				    		// sd 카드에 사용할 폴더있는지 검사후 없으면 생성.
				    		File photoFile = new File(SD_path);
				    		if(!photoFile.exists()){
				    			photoFile.mkdir();
				    		}
				    		SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
				    		String filename = "/eastgem test shoot " + timeStampFormat.format(new Date()).toString() + ".jpg";
	 
				    		// 폴더 생성이나 점검을 완료했으니 파일을 직접 생성하자.
				    		photoFile = new File(SD_path + filename); // 사진이 저장될 경로 및 파일명.
				    		photo_uri = Uri.fromFile(photoFile);
							Log.d("path",photo_uri+"");

			    			// 카메라 Activity 부를때 사용할 인텐트
							Intent intent_Camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent_Camera.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
							intent_Camera.putExtra(MediaStore.EXTRA_OUTPUT, photo_uri);
				    		startActivityForResult(intent_Camera, CAMERA_SHOOT);
			    		}else{
			    		}
						break;
					case 1: // 사진찾기 선택
			            //Picture and video
						if(imageCount<10){
				            intent = new Intent(Intent.ACTION_PICK);
				            intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
				            intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				            startActivityForResult(intent, REQ_CODE_PICK_PICTURE);
						}
			        	 else{
			        		 Toast.makeText(WritePostActivity.this, "이미지는 최대 10장까지 올릴 수 있습니다.", Toast.LENGTH_LONG).show();
			        	 }
						break;
					case 2: // 동영상촬영 선택
						// sd 카드의 mount 여부 검사.
			    		if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
				    		// sd 카드 경로 가져오기
				    		String SD_path = Environment.getExternalStorageDirectory().getAbsolutePath(); //sd 카드 루트경로.
				    		SD_path += "/PostMemories"; // 사용할 폴더. 경로만 지정한것이지 실제로 폴더가 생기거나 한건 아니다.
				    		
				    		// sd 카드에 사용할 폴더있는지 검사후 없으면 생성.
				    		File photoFile = new File(SD_path);
				    		if(!photoFile.exists()){
				    			photoFile.mkdir();
				    		}else{
				    		}
				    		// 파일명 지정.파일명은 유니크 해야 하므로.. 가장 흔한 날짜 시간을 파일명으로 사용한다.
				    		// "eastgem test shoot XXXX-XX-XX XX:XX:XX.jpg" 라는 이름이 될것이다.
				    		SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
				    				//			    				"yyyy-MM-dd"); 
				    		String filename = "/eastgem test shoot " + timeStampFormat.format(new Date()).toString() + ".mp4";
	 
				    		// 폴더 생성이나 점검을 완료했으니 파일을 직접 생성하자.
				    		photoFile = new File(SD_path + filename); // 사진이 저장될 경로 및 파일명.
				    		photo_uri = Uri.fromFile(photoFile);

			    			// 카메라 Activity 부를때 사용할 인텐트
				    		Intent intent_Camera = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				    		intent_Camera.putExtra(MediaStore.EXTRA_OUTPUT, photo_uri);
				    		startActivityForResult(intent_Camera, CAMERA_SHOOT);
			    		}else{
			    		}
						break;
					default:
						break;					
				}
			}
		};		

		@Override
		 public void onConfigurationChanged(Configuration newConfig) {
		         super.onConfigurationChanged(newConfig);
		 }
}